let tabNum = 0; // 当前选中第几个tab标题
const util = require('../../utils/click.js');
const req = require('../../utils/request.js')
const app = getApp()
Page({
  data: {
    winHeight: "", // 窗口高度
    currentTab: 0, // 预设当前项的值
    scrollLeft: 0, // tab标题的滚动条位置
    tabName: [], // tab标题的名字
    size:10,
    page:1,
    userInfo: {},
    loginInfo: {
      title: '微信授权',
      content: '获得您的公开信息(昵称、头像等)',
      logName: 'Gayhub',
      logImage: '../../img/logo.jpg',

    },
    hasUserInfo: false,
    content:[],
    choosedTabInformation: "",// 当前选中tab标题的信息
    carouselList:[
      {
        img: "../../img/img1.jpg"
      },
      {
        img: "../../img/img2.jpg"
      },
       {
        img: "../../img/img3.jpg"
      }
    ]
  },
  onConfirm(e) { // 点击允许
    let dialogComponent = this.selectComponent('.wxc-dialog');
    dialogComponent && dialogComponent.hide();
    let userInfo = JSON.parse(e.detail.detail.rawData)
    this.getType()
    if (!userInfo) {
      return;
    }
    this.setData({
      userInfo: userInfo
    })
    let data = {
      photo: userInfo.avatarUrl,
      nickname: userInfo.nickName,
    }
    this.saveUser(data)
    wx.setStorageSync('userInfo', userInfo)
  },
  saveUser(data){
    let self = this
    req.networkpost("v1/user/addUserInfo", data).then((res) => {
      if (res.data.result_code == 200) {
        console.log("用户信息保存")
      } else {
        wx.showToast({
          title: res.data.message,
        })
      }
    });
  },
  onCancel() { // 点击拒绝
    let dialogComponent = this.selectComponent('.wxc-dialog');
    dialogComponent && dialogComponent.hide();
  },
  more_tab(){
    wx.navigateTo({
      url: '../../pages/tab/tab',
    })
  },
  onShow() {
    // 登录
    let sessionId = wx.getStorageSync("token")
    if (sessionId !== "" && sessionId!==null){
      this.getWindowHeight(); // 高度自适应（rpx）
      this.getType()
    }else{
      this.getToken()
      setTimeout(() => {
        this.getWindowHeight(); // 高度自适应（rpx）
        this.getType()
      }, 1000)
    }

  },

  // 左右滚动tab标题，切换标签
  switchTab: function (e) {
    let current = e.detail.current;
    let cateid = e.target.dataset.cateid;
    this.setData({
      currentTab: current
    });
    console.log("当前选中tab标题", current);
    this.getIndexInfo(cateid); //  获取当前选中tab标题的信息
  },
  getToken(){
    let self=this
    wx.login({
      success: res => {
        wx.request({
          url: 'https://factory.yummyn.com/api/v1/user/getLoginToken',
          data: {
            code: res.code
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
          },
          method: 'POST',
          success: function (res) {
       
            wx.setStorageSync('token', res.data.result.token);
         
          }
        })
      }
    })
  },
  // 点击tab标题，切换当前页
  swichNav: function (e) {
    console.log("点击tab标题", e.target.dataset.current);
    let cur = e.target.dataset.current;
    let cateid = e.target.dataset.cateid;
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
    this.getIndexInfo(cateid); 
  },


  details_jump(e){
    let title = e.currentTarget.dataset.title;
    let cid = e.currentTarget.dataset.aid;
    wx.navigateTo({
      url: '../../pages/details/details?title='+title+"&cid="+cid,
    })
  },
 


  /****************    高度自适应（rpx）    ****************/
  getWindowHeight: function () {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        let clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth; //比例
        console.log(clientHeight);
        console.log(clientWidth);
        let calc = clientHeight * rpxR; 
        console.log(calc);
        that.setData({
          winHeight: calc
        });
      }
    });
  },

  onLoad: function (options) {
    let sessionId = wx.getStorageSync("token")
    let dialogComponent = this.selectComponent('.wxc-dialog');
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: res => {
                app.globalData.userInfo = res.userInfo
                wx.setStorageSync('userInfo', res.userInfo)
                dialogComponent && dialogComponent.hide();
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
              }
            })

        } else {
          dialogComponent && dialogComponent.show();
        }
      }
    })

  },
getIndexInfo(id){
  let that=this
  let data={
    category_id: id,
    size:this.data.size,
    page:this.data.page
  }
  req.networkget("v1/article/getCategoryArticles", data).then(res=>{
    if(res.data.result_code==200){
      that.setData({
        content:res.data.result
      })
    }else{
      wx.showToast({
        title: res.data.message,
      })
    }
  }).catch(res=>{
    wx.showToast({
      title: "请求失败"
    })
  })
},
  /****************    获取头部导航栏tab标题的名字    ****************/
  getType() {
    let self = this
    req.networkpost("v1/category/getIndexCategories", {}).then((res) => {
     if(res.data.result_code==200){
       self.setData({
         tabName: res.data.result
       })
       self.getIndexInfo(res.data.result[0].cateid);
     }else{
       wx.showToast({
         title:res.data.message,
         success(){
           self.getToken()
         }
       })
     }
    });
  },


})